﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Device.Entitys;
using Modules.Device.Repositories;
using PmSoft;
using PmSoft.Exceptions;

namespace Modules.Device;

[UseDI(ServiceLifetime.Scoped)]
public class CheckinDeviceService
{
    private readonly CheckinDeviceRepository projectCheckinDeviceRepository;

    public CheckinDeviceService(CheckinDeviceRepository projectCheckinDeviceRepository)
    {
        this.projectCheckinDeviceRepository = projectCheckinDeviceRepository;
    }

    public IPagedList<CheckinDevice> GetProjectCheckinDevices(CheckInDeviceQuery query, int pageIndex, int pageSize)
    {
        return projectCheckinDeviceRepository.ProjectCheckinDevices(query, pageIndex, pageSize);
    }

    public CheckinDevice? GetProjectCheckinDevice(int id)
    {
        return projectCheckinDeviceRepository.Get(id);
    }

    public IEnumerable<CheckinDevice> GetProjectCheckinDevices(IEnumerable<int> ids)
    {
        return projectCheckinDeviceRepository.PopulateEntitiesByEntityIds(ids);
    }

    public CheckinDevice? GetProjectCheckinDevice(string code)
    {
        return projectCheckinDeviceRepository.GetProjectCheckinDeviceByCode(code);
    }

    public IEnumerable<CheckinDevice> GetProjectCheckinDevicesByProjectId(int projectId)
    {
        return projectCheckinDeviceRepository.GetProjectCheckinDevicesByProjectId(projectId);
    }

    public IEnumerable<CheckinDevice> GetProjectCheckinDevicesByProjectIds(IEnumerable<int> projectIds)
    {
        return projectCheckinDeviceRepository.GetProjectCheckinDevicesByProjectIds(projectIds);
    }

    public void Create(CheckinDevice projectCheckinDevice)
    {
        projectCheckinDevice.CreateTime = DateTime.Now;
        if (projectCheckinDeviceRepository.ExistsByPrjIdAndcode(projectCheckinDevice))
            throw new BusinessException($"项目id：{projectCheckinDevice.ProjectId} 已存在 {projectCheckinDevice.Code} 设备编号，不能创建");
        projectCheckinDeviceRepository.Insert(projectCheckinDevice);
    }

    public void Update(CheckinDevice projectCheckinDevice)
    {
        if (projectCheckinDeviceRepository.ExistsByPrjIdAndcode(projectCheckinDevice, projectCheckinDevice.Id))
            throw new BusinessException($"项目id：{projectCheckinDevice.ProjectId} 已存在 {projectCheckinDevice.Code} 设备编号，不能编辑");
        projectCheckinDeviceRepository.Update(projectCheckinDevice);
    }

    public void Delete(int id)
    {
        projectCheckinDeviceRepository.DeleteByEntityId(id);
    }

    public void Deletes(IEnumerable<int> ids)
    {
        foreach (var id in ids)
        {
            Delete(id);
        }
    }
}